package com.homegoods.shoppingcar.presenter;

import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.homegoods.aroutercomment.ARouterPath;
import com.homegoods.classify.model.Constant;
import com.homegoods.goods.model.GoodsModel;
import com.homegoods.resource.HomeGoodsApp;
import com.homegoods.shoppingcar.R;
import com.homegoods.shoppingcar.ShoppingApiUtils;
import com.homegoods.shoppingcar.item.ShoppingCarEmptyItem;
import com.homegoods.shoppingcar.item.ShoppingGroupItem;
import com.homegoods.shoppingcar.model.GoodsBean;
import com.homegoods.shoppingcar.model.ShoppingCartBean;
import com.kedll.library.adapter.MultiTypeAdapter;
import com.kedll.library.dialog.ECAlertDialog;
import com.kedll.library.mvp.AbstractRefreshPresenter;
import com.kedll.library.mvp.BaseModel;
import com.kedll.library.mvp.RefreshingView;
import com.kedll.library.util.CollectionUtils;
import com.kedll.library.util.ToastUtil;
import com.kedll.library.util.Tuple2;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author QiQi
 * @ClassName: ShoppingPresenter
 * @date 2018/9/12
 * @description
 */
public class ShoppingPresenter extends AbstractRefreshPresenter<RefreshingView> {

    /**
     * 空购物车
     */
    private ShoppingCarEmptyItem carEmptyItem;
    /**
     * 为你推荐
     */
    private ShoppingGroupItem groupItem;

    private int goodsCount;

    /**
     * 是否全选
     */
    private boolean isSelectAll = false;

    private List<ShoppingCartBean> mListGoods = new ArrayList<>();

    private OnShoppingCartChangeListener changeListener;
    private View.OnClickListener listener = v -> {
        int i = v.getId();
        //main
        if (i == R.id.ll_selectAll) {
            selectAll(v.findViewById(R.id.iv_selectAll));

        } else if (i == R.id.btn_submit) {
            if (ShoppingCartBiz.hasSelectedGoods(mListGoods)) {
                ToastUtil.showToast("结算跳转");
                ARouter.getInstance()
                        .build(ARouterPath.PATH_CONFIRM_ORDER)
                        .withString("contents", JSON.toJSONString(setOrderInfoList()))
                        .withString("price", getPrice())
                        .withString("dayang", getDayang())
                        .navigation();
            } else {
                ToastUtil.showToast("亲，先选择商品！");
            }

        } else if (i == R.id.shopping_group_check) {
            groupSelected(v);

            //child
        } else if (i == R.id.cb_goods) {
            childSelected(v);

        } else if (i == R.id.shopping_addandreduce) {
            ShoppingCartBiz.addOrReduceGoodsNum((GoodsBean) v.getTag());
            setSettleInfo();

        } else if (i == R.id.tv_del) {
            showDelDialog();
        }
    };

    /**
     *
     */
    private  List<String> setOrderInfoList() {
        List<String> content= new ArrayList<>();
        for (ShoppingCartBean bean : mListGoods) {
            if (CollectionUtils.isEmpty(bean.getGoods())) {
                continue;
            }
            if (bean.isGroupSelected()) {
                List<Map<String, Object>> list2 = new ArrayList<>();
                for (GoodsBean goods : bean.getGoods()) {
//                    if (content.size()>0){
//                        content.add(",");
//                    }
                    content.add(goods.getGoodsID());
                }
            }
        }
        return content;
    }

    public ShoppingPresenter(RefreshingView mView) {
        super(mView);
        adapter.clear();
        carEmptyItem = new ShoppingCarEmptyItem();
        groupItem = new ShoppingGroupItem();

    }

    @Override
    protected void addHead() {
        super.addHead();
        isSelectAll = false;
        selectAll();
    }

    @Override
    protected void fetchData(boolean isLoadMore) {
        //此处是否登录检查，网络连接失败的情况下检查，并跳转到登录界面
        if (!HomeGoodsApp.isLogin()) {
            ARouter.getInstance()
//                    .build(ARouterPath.PATH_LOGIN_SMS)
                    .build(ARouterPath.PATH_USER_LOGIN)
                    .navigation();
            return;
        }
        if (!isLoadMore) {
            refresh();
        } else {
            addSubscription(getRecommendGoods().subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(goodsModels -> parserData(true, goodsModels)));
        }
    }

    @Override
    public MultiTypeAdapter getAdapter() {
        adapter.setOnItemClickListener((MultiTypeAdapter.OnItemClickListener<BaseModel>) (v, iItem) -> {
            listener.onClick(v);
            if (v.getId() == R.id.shopping_group_check) {
                //店铺点击
                //获取店铺在列表中的位置
                int groupIndex = adapter.findPos(iItem);
                int goodsCount = ShoppingCartBiz.getGoodsCount(mListGoods, ((ShoppingCartBean) iItem.getData()).getGroupItemPosition());
                //刷新店铺下的商品选择状态
                adapter.notifyItemRangeChanged(groupIndex, goodsCount + 1);
            } else if (v.getId() == R.id.cb_goods) {
                //购物车商品点击
                //获取商品在列表中的位置
                int goodsPosition = adapter.findPos(iItem);
                //获取商品在店铺表中的位置
                int goodsIndex = ((GoodsBean) iItem.getData()).getChildPosition();
                //刷新店铺
                adapter.notifyItemChanged(goodsPosition - goodsIndex - 1);
            }
        });
        return adapter;
    }

    /**
     * 刷新界面，请求购物车数据和推荐商品数据
     */
    private void refresh() {
        addSubscription(Observable.zip(getShoppingCar(), getRecommendGoods(), Tuple2::new)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    mListGoods = o.getT0();
                    for (int i = 0; i < CollectionUtils.size(mListGoods); i++) {
                        ShoppingCartBean cartBean = mListGoods.get(i);
                        if (CollectionUtils.isEmpty(cartBean.getGoods())) {
                            continue;
                        }
                        //设置当前组的序号
                        cartBean.setGroupItemPosition(i);
                        adapter.addItem(cartBean.createItem(adapter));
                        for (int j = 0; j < CollectionUtils.size(cartBean.getGoods()); j++) {
                            GoodsBean goodsModel = cartBean.getGoods().get(j);
//                            goodsModel.setGoodsLogo(Constant.TEST_IMG_URL + new Random().nextInt());
                            //设置所属组的序号
                            goodsModel.setGroupPosition(i);
                            //设置在当前组中的序号
                            goodsModel.setChildPosition(j);
                            adapter.addItem(goodsModel.createItem(adapter));
                        }
                    }
                    adapter.addItem(groupItem);
                    goodsCount = adapter.getItemCount();
                    setSettleInfo();

                    List<GoodsModel> goodsModels = o.getT1();
                    parserData(false, goodsModels);
                }, throwable -> {
                    if ("token验证有误！".equals(throwable.getMessage())) {
                        ARouter.getInstance()
                                .build(ARouterPath.PATH_LOGIN)
                                .navigation();
                    }
                }));
    }

    /**
     * 获取推荐商品
     *
     * @return
     */
    private Observable<List<GoodsModel>> getRecommendGoods() {
        return Observable.range(0, 10)
                .map(integer -> {
                    GoodsModel model = new GoodsModel();
                    model.setSmallPic(Constant.TEST_IMG_URL + new Random().nextInt(100));
                    model.setTitle("美的（Midea）电饭煲 钻石纹理上盖 金属拉丝机身");
                    GoodsModel.Businessman businessman = new GoodsModel.Businessman();
                    businessman.setTitle("美的（Midea）电饭煲 钻石纹理上盖 金属拉丝机身");
                    model.setBusinessman(businessman);
                    model.setPayCake(new BigDecimal(0));
                    model.setNowPrice(new BigDecimal(100));
                    return model;
                })
                .buffer(10);
    }

    /**
     * 请求购物车数据
     *
     * @return
     */
    private Observable<List<ShoppingCartBean>> getShoppingCar() {
        return ShoppingApiUtils.getShoppingList();
    }

    /**
     * 通知刷新合计总价
     */
    private void setSettleInfo() {
        String[] infos = ShoppingCartBiz.getShoppingCount(mListGoods);
        if (changeListener != null && infos != null) {
            changeListener.onDataChange(infos[0], infos[1]);
        }
    }

    /**
     * h获取要购买商品的总价
     *
     * @return
     */
    private String getPrice() {
        String[] infos = ShoppingCartBiz.getShoppingCount(mListGoods);
        return infos[1];
    }

    /**
     * 获取要购买商品的大洋总价
     *
     * @return
     */
    private String getDayang() {
        String[] infos = ShoppingCartBiz.getShoppingCount(mListGoods);
        return infos[2];
    }

    /**
     * 通知切换全选状态
     */
    private void selectAll() {
        if (changeListener != null) {
            changeListener.onSelectItem(isSelectAll);
        }
    }

    private void showDelDialog() {
        String selectCount = ShoppingCartBiz.getSelectCount(mListGoods);

        if ("0".equals(selectCount)) {
            ToastUtil.showToastForGravity("您还没选择宝贝哦(*^__^*)", Gravity.CENTER);
            return;
        }

        ECAlertDialog dialog = ECAlertDialog.buildAlert(mView.getContext(), String.format("确定删除这%s种商品吗?", selectCount), (dialog1, which) -> {
            delGoods();
            setSettleInfo();
            adapter.notifyDataSetChanged();
            dialog1.dismiss();
        });
        dialog.show();
    }

    private void delGoods() {
        Iterator<ShoppingCartBean> beanIterator = mListGoods.iterator();
        List<GoodsBean> goodsDel = new ArrayList<>();
        while (beanIterator.hasNext()) {
            ShoppingCartBean cartBean = beanIterator.next();
            if (cartBean.isGroupSelected()) {
                beanIterator.remove();
                goodsDel.addAll(cartBean.getGoods());
                int index = adapter.findPos(cartBean.getItem());
                adapter.removeItemRange(index, cartBean.getGoods().size() + 1);
                adapter.notifyItemRangeRemoved(index, cartBean.getGoods().size() + 1);
                goodsCount -= cartBean.getGoods().size() + 1;
            } else {
                Iterator<GoodsBean> goodsBeanIterator = cartBean.getGoods().iterator();
                while (goodsBeanIterator.hasNext()) {
                    GoodsBean goods = goodsBeanIterator.next();
                    if (goods.isChildSelected()) {
                        goodsBeanIterator.remove();
                        adapter.removeItem(goods.getItem());
                        int index = adapter.findPos(goods.getItem());
                        adapter.notifyItemRemoved(index);
                        goodsCount--;
                        goodsDel.add(goods);
                    }
                }
            }
        }

        if (CollectionUtils.isNotEmpty(goodsDel)) {
            ShoppingCartBiz.delGood(goodsDel);
        }

        for (int i = 0; i < CollectionUtils.size(mListGoods); i++) {
            ShoppingCartBean cartBean = mListGoods.get(i);
            if (CollectionUtils.isEmpty(cartBean.getGoods())) {
                continue;
            }
            //设置当前组的序号
            cartBean.setGroupItemPosition(i);
            for (int j = 0; j < CollectionUtils.size(cartBean.getGoods()); j++) {
                GoodsBean goodsModel = cartBean.getGoods().get(j);
                //设置所属组的序号
                goodsModel.setGroupPosition(i);
                //设置在当前组中的序号
                goodsModel.setChildPosition(j);
            }
        }
    }

    /**
     * 商品切换选中状态
     *
     * @param v
     */
    private void childSelected(View v) {
        String tag = String.valueOf(v.getTag());
        if (tag.contains(",")) {
            String[] s = tag.split(",");
            int groupPosition = Integer.parseInt(s[0]);
            int childPosition = Integer.parseInt(s[1]);
            isSelectAll = ShoppingCartBiz.selectOne(mListGoods, groupPosition, childPosition);
            selectAll();
            setSettleInfo();
        }
    }

    /**
     * 店铺切换选中状态
     *
     * @param v
     */
    private void groupSelected(View v) {
        addSubscription(Observable.just(String.valueOf(v.getTag()))
                .map(Integer::parseInt)
                .map(groupPosition -> ShoppingCartBiz.selectGroup(mListGoods, groupPosition))
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aBoolean -> {
                    isSelectAll = aBoolean;
                    selectAll();
                    setSettleInfo();
                })

        );

    }

    public View.OnClickListener getListener() {
        return listener;
    }

    /**
     * 显示空购物车
     */
    public void showEmpty() {
        if (!adapter.getValues().contains(carEmptyItem)) {
            adapter.addItem(0, carEmptyItem);
            adapter.notifyItemInserted(0);
            isSelectAll = false;
            goodsCount++;
        }
    }

    /**
     * 全选
     *
     * @param cbSelectAll
     */
    private void selectAll(ImageView cbSelectAll) {
        isSelectAll = ShoppingCartBiz.selectAll(mListGoods, isSelectAll, cbSelectAll);
        setSettleInfo();
        adapter.notifyItemRangeChanged(0, goodsCount + 1);
    }

    public void setOnChangeListener(OnShoppingCartChangeListener changeListener) {
        this.changeListener = changeListener;
    }

    /**
     * 获取除去推荐商品外的item总数
     *
     * @return
     */
    public int getGoodsCount() {
        return goodsCount;
    }
}
